package org.os.framework.extensions.web.filter;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.os.framework.context.config.SecurityConfig;
import org.os.framework.extensions.web.wrapper.DecryptHttpRequest;
import org.springframework.context.annotation.Configuration;

import lombok.extern.slf4j.Slf4j;

/**
 * @author
 */
@Slf4j
@Configuration
public class DecryptHttpFilter implements Filter {

    @Resource
    private SecurityConfig security;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        if (!(request instanceof HttpServletRequest)) {
            chain.doFilter(request, response);
            return;
        }
        if (!security.getDecrypt()) {
            chain.doFilter(request, response);
            return;
        }
        // todo
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        DecryptHttpRequest decryptRequest = new DecryptHttpRequest(httpRequest);
        String reqeustBody = new String(decryptRequest.getBody());
        log.info("original = {}", reqeustBody);
        String decrypted = security.decrypt(reqeustBody);
        decryptRequest.setBody(decrypted.getBytes());
        chain.doFilter(decryptRequest, response);

    }

}
